from configobj import ConfigObj

import es
import langlib
import playerlib

from wcs.libs.constants import *
from wcs.libs.config import *

__all__ = ["messages", "languages"]

class StringsManager(langlib.Strings):
    """
    This object manages all multi-text string. It allows us to do shortcut
    messages so we don't have to type out all of the prefixes each time.
    """
    def __init__(self):
        """
        Default constructor, assign all paths and open all files.
        """
        self.langPath = DATA_PATH.joinpath("wcsstrings.ini")
        langlib.Strings.__init__(self, str(self.langPath))

    def send(self, users, identifier, tokens={}, prefix=True):
        """
        This function allows us to send messages to users very easily by
        implicitly executing default actions. This will apply this mod's prefix,
        and set up any colouring for multi-lingual text based upon the
        identifier passed and will automatically retrieve a player's language.

        @param list users A list of users to send the message to
        @param string identifier An identifier to specify the message to send
        @param dict tokens Dictionary containing values to replace in the string
        @param bool prefix Whether or not the message will contain the prefix
        """
        if not hasattr(users, "__iter__"):
            users = (users, )
        for userid in users:
            message = ""
            if str(modPrefix) and prefix:
                message += "#green%s #default- " % modPrefix
            language = playerlib.getPlayer(userid).get("lang")
            langlibString = self.expand(identifier, tokens, language)
            message += "#lightgreen%s" % langlibString
            es.tell(userid, "#multi", message)

    def __call__(self, userid, identifier, tokens={}):
        """
        Executed when the singleton instnace is treated as a function. Assume
        that we want to retrieve the identifier for the user based upon
        their default language and replace the strings with the tokens.

        @param integer userid The ID of the user to get the text for
        @param string identifier The langlib identifier for the ConfigObj
        @param dict tokens Any tokens to replace into the string
        @return string The language identifier for the user
        """
        language = playerlib.getPlayer(userid).get("lang")
        return self.expand(identifier, tokens, language)

class LanglibManager(ConfigObj):
    """
    This object will store all langlib text strings. It will basically be a
    dictionary with special functions and attributes.
    """
    def addLangString(self, race, langlibStrings):
        """
        This function will add a langlib.Strings() object for a specific race.
        This is to support functionality for old styling languages by having
        each text.ini inside the race folder itself. This will take the langlib
        String object from that file and append it to the global strings and
        enable us to save it to the main global langlib file.

        @param string race The name of the race this string represents
        @param langlib.Strings langlibStrings The strings object of a race text
                                              file.
        """
        if not self.__contains__(race):
            self.__setitem__(race, {})
        for key, value in langlibStrings.iteritems():
            self.__getitem__(race).__setitem__(key, value.copy())

    def save(self):
        """
        Saves all lanugages to the global file location. Write the file. As
        ConfigObj saves the file with the line seperator of \n by default, we
        need to test if the os.linesep differs. If so, then we need to open
        the source and replace everything so that the lines correctly display
        on systems such as NT etc.
        """
        self.write()
        if os.linesep != "\n":
            fileHandle = open(self.filename, 'rb')
            newSource = fileHandle.read().replace('\n', os.linesep)
            fileHandle.close()
            fileHandle = open(self.filename, 'wb')
            fileHandle.write(newSource)
            fileHandle.close()

languagePath = DATA_PATH.joinpath("racestrings.ini")
languages    = LanglibManager(str(languagePath), file_error=False,
                                                             create_empty=True)
messages     = StringsManager()